package com.webdev.dao.imp;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.PreparedStatement;
import com.webdev.dao.RequestDao;
import com.webdev.domain.Personnel;
import com.webdev.domain.Request;

public class RequestDaoImp implements RequestDao {
	static MySql mysql = new MySql();
	private static List<Request> search(String sql) {
		List<Request> reqlist= new ArrayList<Request>();
		Connection con=mysql.getConn();
	    PreparedStatement pstmt;
	    try {
	    	
	        pstmt = (PreparedStatement)con.prepareStatement(sql);
	        ResultSet rs = pstmt.executeQuery();
	        while(rs.next()){  
	            Request reqa=new Request();  
	            reqa.setRid(rs.getInt("rid"));  
	            reqa.setRsdate(rs.getDate("rsdate"));  
	            reqa.setRedate(rs.getDate("redate"));  
	            reqa.setRtype(rs.getString("rtype"));
	            reqa.setRinfo(rs.getString("rinfo"));
	            reqa.setPid(rs.getInt("pid"));
	            reqa.setRstate(rs.getString("rstate"));
	            reqlist.add(reqa);  
	        } 
	        pstmt.close();
	        con.close();
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
		return reqlist;
	}

    public void addRequest(Request req) {
    	String sql = "insert into req(rsdate,redate,rtype,rinfo,pid,rstate) values('"
    			     + req.getRsdate() + "','"
    			     + req.getRedate() + "','"
    			     + req.getRtype() + "','"
    			     + req.getRinfo() + "',"
    			     + req.getPid() + ",'待审核');";
    	System.out.println(sql);
    	mysql.add(sql);
    }
    /*
     * 老板查看请假单返回所有人的请假单
     * */
	@Override
	public List<Request> bossSearch() {	    
	    String sql="select * from req";
	    return search(sql);	    
	}
	/*
	 * 员工查看请假单返回查询的人的请假单
	 * */
	@Override
	public List<Request> staffSearch(Personnel personnel) {
	    String sql="select * from req where pid = " + personnel.getPid() + ";";
	    return search(sql);
	    
	}
	@Override
	public void updateRequest(Request req) {
		String sql="update req set rsdate='"
	                + req.getRsdate() + "',redate='"
	                + req.getRedate() + "',rtype='"
	                + req.getRtype() + "',rinfo='"
	                + req.getRinfo() + "',rid="
	                + req.getRid() + ",rstate='"
	                + req.getRstate() + "' where rid="
				    + req.getRid() + ";";
		mysql.update(sql);		
	}

	@Override
	public Request getRequestById(int rid) {
		String sql = "select * from req where rid = " + rid + ";";
		List<Request> reqlist = new ArrayList<Request>();
		reqlist = search(sql);
		return reqlist.get(0);
	}
}
